//
//  MusicSmartMusicViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit
import JXSegmentedView
class MusicSmartMusicViewController: UIViewController, JXSegmentedListContainerViewListDelegate {
    var disposeBag = DisposeBag()
    var viewModel = MusicViewModel()
    
    var dataArr:[MusicModel] = []
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: MusicMusicDefualtCell.self)
        view.register(cellWithClass: MusicSmartDescCell.self)
        view.rowHeight = UITableView.automaticDimension
        view.sectionHeaderHeight = 0
        view.estimatedSectionHeaderHeight = 0
        view.sectionFooterHeight = 0
        view.estimatedSectionFooterHeight = 0
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        return view
    }()
    
    private lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "创作音乐"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.allRound(24)
        return button
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getDesc()
        self.view.addSubview(tableView)
        self.view.addSubview(saveBtn)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-8)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
        }
        
        viewModel.getHomeList()
        bindEvent()
        XLog.d("", "1")
        
     
    }
    
    func musicGuide(){
        let videoGuideView = MusicGuideView()
        videoGuideView.initUI(rect: CGRect(x: 8, y: 66, width: SCREEN_WIDTH - 16, height: 68.0 * 3 + 10))
        Appearance.addViewToWindow(videoGuideView)
        videoGuideView.nextGuideBag = { [weak self] in }
    }
//    var a:Bool = false
//    func videoGuide(){
//        if a {
//            return
//        }
//        a = true
//        let videoGuideView = HomeMusicGuideView()
//        let rect = getSectionPosition(section: 0) ?? CGRect.zero
//        videoGuideView.initUI(rect: rect)
//        Appearance.addViewToWindow(videoGuideView)
//        videoGuideView.nextGuideBag = { [weak self] in }
//    }
//    
    func getSectionPosition(section:Int) -> CGRect? {
        if tableView.numberOfSections > section {
            let sectionRect = tableView.rectForHeader(inSection: section)
            let convertedRect = tableView.convert(sectionRect, to: tableView.superview)
            return convertedRect
        }
        return nil
    }
    
    func bindEvent(){
        viewModel.reloadHomeDataSubject.subscribe(onNext: {[weak self] models in
            self?.dataArr = models
            self?.tableView.reloadData()
            
            if self?.dataArr.count ?? 0 > 0 {
                let userDefaults = UserDefaults.standard
//                userDefaults.set(false, forKey: firstLaunchNewMusicGuideKey)
                if userDefaults.bool(forKey: firstLaunchNewMusicGuideKey) == false {
                    userDefaults.set(true, forKey: firstLaunchNewMusicGuideKey)
                    self?.musicGuide()
                }
            }
        }).disposed(by: disposeBag)
        
        viewModel.reloadListSubject.subscribe(onNext: {[weak self] models in
            self?.tableView.reloadData()
        }).disposed(by: disposeBag)
        
        
        saveBtn.setClosureTouchUpInside_k { [weak self] in
            self?.showBuyVideo()
        }
        
        viewModel.createSuccessSubject.subscribe(onNext: {[weak self] checkId in
            let vc = MusicGenerateViewController()
            vc.checkId = checkId
            self?.navigationController?.pushViewController(vc)
        }).disposed(by: disposeBag)
    }
    
    var lose:Int = 0
    func getDesc(){
        self.lose = 200
    }
    
    func showBuyVideo(){
        if !Appearance.shared.isLoign {
            GlobalRx.loginSubject.onNext(())
            return
        }
        guard let desc = self.viewModel.lyric_desc else {
            NDProgressHUD.show(message: "请输入歌曲描述")
            return
        }
        guard desc.count >= 8 else {
            NDProgressHUD.show(message: "请输入描述，最少 8 个字符")
            return
        }
        if let score = Appearance.shared.accoutModel?.userOtherInfo?.score {
            if score < Int(self.lose) {
                self.nomoreScore(score: score)
            }else {
                self.generatePOPView(score: score)
            }
        }
    }
    
    func nomoreScore(score:Int){
        let user = Appearance.shared.accoutModel
        if user?.userOtherInfo?.is_vip == 1 {
            let view = VideoTopupView()
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = DiamondBuyViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }else {
            let view = VideoTopupView()
            view.titleLabel.text = "钻石余额不足, 升级会员可获增钻石"
            view.confirmButton.titleForNormal = "立即升级"
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = SubscribeViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func generatePOPView(score:Int){
        let view = VideoBuyView()
        Appearance.addViewToWindow(view)
        view.initViews(money: "\(score)", lose: "\(self.lose)", title: "生成音乐将花费\(self.lose)钻石")
        view.chooseDone = { [weak self] in
            self?.viewModel.musicCreate()
        }
    }
    
    func listView() -> UIView {
        return self.view
    }

}
extension MusicSmartMusicViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.dataArr.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: MusicMusicDefualtCell.self)
            cell.setup(model: self.dataArr[indexPath.item])
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withClass: MusicSmartDescCell.self)
            cell.descTextView.text = self.viewModel.lyric_desc ?? ""
            cell.chooseDesc = { [weak self] text in
                self?.viewModel.lyric_desc = text
            }
            cell.buttonBtn.setClosureTouchUpInside_k { [weak self] in
                self?.viewModel.generateDesc()
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let model = self.dataArr[indexPath.item]
            let vc = MusicPlayerDetailsViewController()
            vc.model = model
            self.navigationController?.pushViewController(vc)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return UITableView.automaticDimension
        }else {
            return 230
        }
    }

    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 10 {
            kHideKeyboard()
        }
    }
}
